
package com.progroup.graphics;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Spinner;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.progroup.checks.Checks;
import com.progroup.kyrsmoney.R;
import com.progroup.kyrsmoney.database.DBAdapter;
import com.progroup.kyrsmoney.dialog.CustomDialog;
import com.progroup.kyrsmoney.preferences.PreferencesActivity;



public class GraphicsChart extends SherlockFragmentActivity {
	/** Called when the activity is first created. */
	private GraphicalView BarChartView;
	SharedPreferences pref;
	private String[] NAME_BANK;
	private String[] ID_BANK;
	private double[] DATE;
	private double[] COORDINATE;
	private String MONEY1="usd"; 
	private String MONEY2="buy";
	private int [] rtyq = {0,0};
	private String[] buy_sale; //= {"Покупка", "Продажа"};
	private String [] usd_eur; //= {"Доллар", "Евро", "Рубль"};
	private int LENGTH_BANK;
	private List<Date[]> dates = new ArrayList<Date[]>();
	List<double[]> values = new ArrayList<double[]>();
	CustomDialog dialog;
	int[] colors = new int[] {Color.YELLOW,Color.RED,Color.BLUE,Color.CYAN,Color.GREEN,Color.MAGENTA, Color.LTGRAY, Color.WHITE};
	ActionBar actionbar = null;
	
	Spinner spinner1;
	Spinner spinner2;
	LinearLayout layout ;
	
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.graphics);
		buy_sale = new String[]{this.getText(R.string.graphic_buy).toString(), this.getText(R.string.graphic_sale).toString()};
		usd_eur = new String[]{getText(R.string.graphic_usd).toString(), getText(R.string.graphic_eur).toString(), getText(R.string.graphic_rub).toString()};
		actionbar = getSupportActionBar();
		Drawable myIcon = getResources().getDrawable( R.drawable.action_bar_fon);
		actionbar.setBackgroundDrawable(myIcon);
		
		
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		
		pref = PreferenceManager.getDefaultSharedPreferences(this);
		
		layout= (LinearLayout) findViewById(R.id.liner);  
		spinner1 = (Spinner)findViewById(R.id.spinner1);
		spinner2 = (Spinner)findViewById(R.id.spinner2);
		ArrayAdapter<String> feat_adapter1 = new ArrayAdapter<String>(GraphicsChart.this, R.layout.spintext,  buy_sale);
		feat_adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner1.setAdapter(feat_adapter1);
		spinner1.setAdapter(feat_adapter1);
		ArrayAdapter<String> feat_adapter2 = new ArrayAdapter<String>(GraphicsChart.this, R.layout.spintext,  usd_eur);
		feat_adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner2.setAdapter(feat_adapter2);
		spinner1.setSelection(0);
		spinner2.setSelection(0);
		rtyq[0]=spinner1.getSelectedItemPosition();
		rtyq[1]=spinner2.getSelectedItemPosition();
		spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(rtyq[0]!=arg2){
					rtyq[0]=arg2;
					if(arg2==0){
						MONEY1="buy";
					}else{
						MONEY1="sale";
					}
					layout.removeAllViews();
					dialog = new CustomDialog(GraphicsChart.this, Checks.DIALOG_LOADING, null);
					dialog.show();
					new ParseSite().execute();
				}
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
			
		});
		spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(rtyq[1]!=arg2){
					rtyq[1]=arg2;
					if(arg2==0){
						MONEY2="usd";
					}else if(arg2==1){
						MONEY2="eur";
					}else{
						MONEY2="rub";
					}
					
					layout.removeAllViews();
					dialog = new CustomDialog(GraphicsChart.this, Checks.DIALOG_LOADING, null);
					dialog.show();
					new ParseSite().execute();
				}
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		
		if(spinner1.getSelectedItemPosition()==0){MONEY1="buy";};
		if(spinner1.getSelectedItemPosition()==1){MONEY1="sale";};
		if(spinner2.getSelectedItemPosition()==0){MONEY2="usd";};
		if(spinner2.getSelectedItemPosition()==1){MONEY2="eur";};
		if(spinner2.getSelectedItemPosition()==2){MONEY2="rub";};
		
		dialog = new CustomDialog(GraphicsChart.this, Checks.DIALOG_LOADING, null);
		dialog.show();
		new ParseSite().execute();
		
		
		
		
	}
	
	
	public View ChartView(){
		
		Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(GraphicsChart.this, R.anim.view_animation);
		hyperspaceJumpAnimation.setFillAfter(true);
		
		XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
		XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
		int colo = 0;
		
		
		mRenderer.setXTitle(GraphicsChart.this.getText(R.string.graphic_date).toString());
		//mRenderer.setYTitle("Координаты");
		mRenderer.setXAxisMin(dates.get(0)[0].getTime());
		mRenderer.setXAxisMax(dates.get(0)[(dates.get(0).length-1)].getTime());
		mRenderer.setYAxisMin(min()-0.1);
		mRenderer.setYAxisMax(max()+0.1);
		mRenderer.setAxesColor(Color.BLACK);//obvodka grafica
		mRenderer.setLabelsColor(Color.BLACK);//cvet teksta "Dati"
		mRenderer.setXLabelsColor(Color.BLACK);//cvet koordinat dati
		mRenderer.setYLabelsColor(0, Color.BLACK);
		
		
		
		mRenderer.setZoomButtonsVisible(true);
		
		
		
		
		mRenderer.setXLabels(10);
		mRenderer.setYLabels(10);
		mRenderer.setBackgroundColor(Color.WHITE);//cvet grafika v nytri!!
		mRenderer.setApplyBackgroundColor(true);
		//mRenderer.setMargins(new int[]{50,50,50,50}); //otstyp grafica ot kraev
		mRenderer.setMarginsColor(Color.WHITE);
		
		
		
		mRenderer.setYLabelsAlign(Align.RIGHT);
		
		
		
		
		mRenderer.setChartTitleTextSize(18);
		mRenderer.setLabelsTextSize(14);
		
		mRenderer.setAxisTitleTextSize(14);
		
		mRenderer.setLegendTextSize(14);
		
		
		
		//mRenderer.setMargins(new int[] { 20, 0, 0, 0 });
		
		
		
		//mRenderer.setShowGrid(true); //setka
		//mRenderer.setGridColor(Color.LTGRAY);//cvet setki
		
		for(int i = 0; i<NAME_BANK.length; i++)
		{
			
			TimeSeries series1 = new TimeSeries(NAME_BANK[i]);
			XYSeriesRenderer renderer = new XYSeriesRenderer();
			
			if(BarChartView!=null){
				series1.clear();
			}
			
			renderer.setLineWidth(Integer.parseInt(pref.getAll().get(PreferencesActivity.LINE_WEIGTH)+""));
			
			if(BarChartView==null){
				
				for(int r = 0; r<DATE.length; r++)
				{
					
					if(values.get(i)[r] != 0){
						series1.add(dates.get(i)[r], values.get(i)[r]);
					}
				}
				mDataset.addSeries(series1);
				
				if(colo==(colors.length-1)){
					colo=0;
				}
				//renderer.setLineWidth(pref.getInt(PreferencesActivity.LINE_WEIGTH, 0));
				renderer.setColor(colors[colo]);
				
				colo++;
				mRenderer.addSeriesRenderer(renderer);
			}else{
				
				for(int r = 0; r<DATE.length; r++)
				{
					if(values.get(i)[r] != 0){
						series1.add(dates.get(i)[r], values.get(i)[r]);
					}
				}
				mDataset.addSeries(series1);
				//Log.i("ElSE", series1.getX(i)+"="+series1.getY(i));
				
				if(colo==(colors.length-1)){
					colo=0;
				}
				renderer.setColor(colors[colo]);
				
				colo++;
				mRenderer.addSeriesRenderer(renderer);
			}
			
			
			
			
		}
		
		
		int length = mRenderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer seriesRenderer = mRenderer.getSeriesRendererAt(i);
			seriesRenderer.setChartValuesTextSize((float) ((Integer.parseInt(pref.getAll().get(PreferencesActivity.LINE_WEIGTH)+"")+12)*1.2));
			if(pref.getBoolean(PreferencesActivity.VISIBLE_COORDINAT, false)){
				seriesRenderer.setDisplayChartValues(true);
			}
		}
		
		
		
		if(BarChartView!=null){
			BarChartView.repaint();
		}
		
		
		BarChartView = ChartFactory.getTimeChartView(GraphicsChart.this, mDataset, mRenderer, "MM/dd");
		//BarChartView.setAnimation(hyperspaceJumpAnimation);
		
		return BarChartView;
	}
	
	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		layout.removeAllViews();
		new ParseSite().execute();
	}
	
	
	
	
	
	
	public void point_coordinat(){
		
		
		
		if(BarChartView!=null){
			values.clear();
		}
		DBAdapter dbHelper = new DBAdapter(GraphicsChart.this);
		dbHelper.open();
		int lengkyrs = ID_BANK.length;
		
		for(int i = 0; i<lengkyrs; i++ ){
			Cursor cursor  = dbHelper.kyrs_banks(Integer.parseInt(ID_BANK[i]),MONEY2, MONEY1);
			int leng = cursor.getCount();
			COORDINATE = new double[leng];
			if (cursor != null) {
				cursor.moveToFirst();
				int r = 0;
				do {
					COORDINATE[r]=Double.parseDouble(cursor.getString(0));
					r++;
				} while (cursor.moveToNext());
			}
			
			cursor.close();
			
			
			values.add(COORDINATE);
			
			
		}
		
		
		dbHelper.close();
		
		
	}
	
	
	
	
	private void KolichBankov(){
		DBAdapter dbHelper = new DBAdapter(GraphicsChart.this);
		dbHelper.open();
		Cursor cursor  = dbHelper.DB_CHART_GET_DATA(0, null);
		
		LENGTH_BANK = cursor.getCount();
		
		
		
		ID_BANK = new String[LENGTH_BANK];
		NAME_BANK = new String[LENGTH_BANK];
		if (cursor != null) {
			cursor.moveToFirst();
			int i = 0;
			do {
				ID_BANK[i]=cursor.getString(0);
				NAME_BANK[i]=cursor.getString(1);
				i++;
			} while (cursor.moveToNext());
		}
		cursor.close();
		
		
		
		
		for(int g = 0; g<=(NAME_BANK.length-1); g++){
			
			Cursor cursor2  = dbHelper.DB_CHART_GET_DATA(1, ID_BANK[0]);
			int leng2 = cursor2.getCount();
			Log.i("DATE", leng2+"");
			DATE = new double[leng2];
			dates.add(new Date[leng2]);
			if (cursor2 != null) {
				cursor2.moveToFirst();
				int i = 0;
				do {
					Log.i("KOLICHESTVO BANKOV",g+"   "+i);
					dates.get(g)[i]=new Date(
							Integer.parseInt(cursor2.getString(0).substring(0, 4)), 
							Integer.parseInt(cursor2.getString(0).substring(4, 6))-1,
							Integer.parseInt(cursor2.getString(0).substring(6, 8))
							);
					DATE[i]=Double.parseDouble(cursor2.getString(0));
					Log.i("DATE!!!!", dates.get(g)[i].getMonth()+"");
					i++;
				} while (cursor2.moveToNext());
			}
			
			cursor2.close();
			
		}
		
		dbHelper.close();
	}
	
	
	
	
	
	public double min(){
		double q = values.get(0)[0];
		for(int i = 0; i<values.size(); i++)
		{
			for(int r=0; r<values.get(i).length; r++)
			{
				if(q>values.get(i)[r])
				{
					if(values.get(i)[r]!=0){
						q=values.get(i)[r];
					}
				}
			}
		}
		return q;
	}
	
	public double max(){
		double q = values.get(0)[0];
		for(int i = 0; i<values.size(); i++)
		{
			for(int r=0; r<values.get(i).length; r++)
			{
				if(q<values.get(i)[r])
				{
					q=values.get(i)[r];
				}
			}
		}
		return q;
	}
	
	private class ParseSite extends AsyncTask<String, Void, List<String>> {
		
		protected List<String> doInBackground(String... params) {
			try{
				KolichBankov();
				point_coordinat();
			}catch (Exception e) {
				// TODO: handle exception
			}
			
			return null;
		}
		
		
		protected void onPostExecute(List<String> output) {
			try {
				layout.addView(ChartView(), new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
			} catch (Exception e) {
				// TODO: handle exception
			}
			try{
				Checks.KeyBack=Checks.KEYBACK_YES;
				if(dialog!=null){
					dialog.dismiss();
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	  @Override 
      public boolean onOptionsItemSelected(MenuItem item) 
      {
    	  switch (item.getItemId())
    	  {
    	  case android.R.id.home:
    	  {
    		 finish();
    		  break;
    		  }
    	  
    	  default: 
    		  return false; 
    	  }
    	  return super.onOptionsItemSelected(item); 
      }
      
	
}